package com.telecom.restaurant.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by qiqi on 2019/12/14.
 */
public class DateUtil {

    private static Logger logger = LoggerFactory.getLogger(DateUtil.class);

    private static final String DATE_FORMAT = "yyyy-MM-dd";

    private static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private static SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat(DATE_FORMAT);

    private static SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat(TIME_FORMAT);

    public static Date convertString2Date(String date) {
        if(StringUtils.isBlank(date)){
            return null;
        }
        try {
            synchronized (DATE_FORMATTER) {
                return DATE_FORMATTER.parse(date);
            }
        } catch (Exception e) {
            logger.error("convert date error. String date:{}", date);
            return null;
        }
    }

    public static Date convertString2Time(String time) {
        if(StringUtils.isBlank(time)){
            return null;
        }
        try {
            synchronized (TIME_FORMATTER) {
                return TIME_FORMATTER.parse(time);
            }
        } catch (Exception e) {
            logger.error("convert date error. String date:{}", time);
            return null;
        }
    }

    public static String convertDate2DateString(Date date) {
        if(date == null){
            return null;
        }
        synchronized (DATE_FORMATTER) {
            return DATE_FORMATTER.format(date);
        }
    }

    public static String convertDate2TimeString(Date date) {
        if(date == null){
            return null;
        }
        synchronized (TIME_FORMATTER) {
            return TIME_FORMATTER.format(date);
        }
    }
}
